package com.vueapi.utils;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.vueapi.constant.ErrorCodeEnum;
import com.vueapi.exception.BlogException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Component
public class QiniuUtils {

    public static  final String url = "http://img.linzhongyue.cn/";

    @Value("${qiniu.accessKey}")
    private  String accessKey;

    @Value("${qiniu.accessSecretKey}")
    private  String accessSecretKey;

    public String saveImage(MultipartFile file) throws IOException {
        try {
            // 构造一个带指定Zone对象的配置类,不同的七云牛存储区域调用不同的zone
            Configuration cfg = new Configuration(Region.huadong());
            // ...其他参数参考类注释
            UploadManager uploadManager = new UploadManager(cfg);
            // 密钥配置
            Auth auth = Auth.create(accessKey, accessSecretKey);
            int dotPos = file.getOriginalFilename().lastIndexOf(".");
            if (dotPos < 0) {
                return null;
            }
            String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
            // 判断是否是合法的文件后缀
            if (!FileUtil.isFileAllowed(fileExt)) {
                return null;
            }

            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
            System.out.println("准备上传图片...");
            // 调用put方法上传
            Response res = uploadManager.put(file.getBytes(), fileName, auth.uploadToken("lzy-blog"));
            System.out.println("上传图片结束...");
            // 打印返回的信息
            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址
                System.out.println("上传图片成功...");
                return url + JSONObject.parseObject(res.bodyString()).get("key");
            } else {
                System.out.println("上传图片失败...");
                return null;
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            throw new BlogException(ErrorCodeEnum.UPLOAD_IMG_ERROR.getCode(),ErrorCodeEnum.UPLOAD_IMG_ERROR.getMsg());
        }
    }
}
